<?
require_once("mvc/action/Action.php");
require_once("cms/newsletter/om/NewsletterPeer.php");

class SaveAction extends Action {

    private $log;

    public function __construct() {
        $this->log =& LoggerManager::getLogger("SaveAction");
    }

    public function execute(ActionConfig &$mapping, &$form, Request &$request, Response &$response) {

        if($mapping->getPath() == "/template") {
            $form->getNewsletter()->setBody($this->getTemplate($request, $form));
            return $mapping->findForward("success");
        }

        $errors = new ActionMessages();

        $newsletter =& $form->getNewsletter();
        $newsletter->setModifiedDate(date(_Core::FORMAT_SQLDATETIME));

        $conn = Propel::getConnection();

        try {

            $conn->begin();

            if($newsletter->getNewsletterId() > 0) {

                NewsletterPeer::doUpdate($newsletter, $conn);

            } else {

                $newsletter->setStatus("draft");
                $newsletter->setInsertDate(date(_Core::FORMAT_SQLDATETIME));
                $newsletter->setNewsletterId(
                    NewsletterPeer::doInsert($newsletter, $conn)
                );

            }

            $conn->commit();

        } catch(PropelException $e) {
            $conn->rollback();
            $errors->add(ActionMessage::GLOBAL_MESSAGE,
                new ActionMessage("error.save"));
            $this->log->error($e->getMessage());
        }


        // Send a test email.
        if(strlen($form->getEmail()) > 0) {

            require_once "swift/Swift.php";
            require_once "swift/Swift/Connection/NativeMail.php";

            try {

                // Start Swift
                $swift = new Swift(new Swift_Connection_NativeMail());

                // Create the message
                $message = new Swift_Message($form->getNewsletter()->getSubject());

                $base = $request->getContext()->getInitParameter(_Newsletter::BASE);

                ob_start();
                include($request->getContext()->getInitParameter(_Newsletter::HEADER));
                $header = ob_get_contents();                
                ob_end_clean();
                
                ob_start();
                include($request->getContext()->getInitParameter(_Newsletter::FOOTER));
                $footer = ob_get_contents();
                ob_end_clean();

                // get some i18n resources
                $resources = $request->getContext()->getAttribute("php-cms-newsletternewsletter");
                $locale = new Locale($request->getContext()->getInitParameter(_Core::DEFAULT_LANGUAGE));
                $text = $resources->getMessage($locale, "mail.text");

                // Add some plain text
                // Todo: Provide online newsletter link.
                $message->attach(
                    new Swift_Message_Part(
                        $text, "text/plain", null, "utf-8"));

                // Add html
                $body = str_replace(
                            array("{base}", "{name}", "{key}"),
                            array($base, "Tester", md5($form->getEmail())),
                            $header.$form->getNewsletter()->getBody()->getContents().$footer
                        );
                        
                $message->attach(new Swift_Message_Part($body, "text/html", null, "utf-8"));

                //Now check if Swift actually sends it
                $swift->send($message, $form->getEmail(), EMAIL_FROM);


            } catch (Swift_Connection_Exception $e) {
                $errors->add(ActionMessage::GLOBAL_MESSAGE,
                    new ActionMessage("There was a problem communicating with MAIL."));
                $this->log->errors($e);
            } catch (Swift_Message_MimeException $e) {
                $errors->add(ActionMessage::GLOBAL_MESSAGE,
                    new ActionMessage("There was an unexpected problem building the email."));
                $this->log->errors($e);
            }

        }


        // Return any save errors.
        if(!$errors->isEmpty()) {
            $this->saveErrors($request, $errors);
            return $mapping->getInputForward();
        }


        // Reset the newsletterListForm from & to session.
        $session  = $request->getSession();
        $listForm = $session->getAttribute("cms/newsletterListForm");
        if(!is_null($listForm)) {
            $listForm->setPage(0);
            $session->setAttribute("cms/newsletterListForm", $listForm);
        }

        // To the success newsletter.
        return $mapping->findForward("success");

    }


    private function getTemplate(Request $request, $form) {
        ob_start();

        include($request->getContext()->getInitParameter(
            $form->getTemplate() == "newsletter" ? _Newsletter::BODY_NEWSLETTER : _Newsletter::BODY_NEWSFLASH));

        $template = str_replace(
                        array("{base}"),
                        array($request->getContext()->getInitParameter(_Newsletter::BASE)),
                        ob_get_contents()
                    );

        ob_end_clean();
        return htmlentities($template);

    }

}
?>